package com.lovo.testjpa.service.impl;

import com.lovo.testjpa.bean.Student;
import com.lovo.testjpa.bean.vo.PageVO;
import com.lovo.testjpa.dao.StudentDAO;
import com.lovo.testjpa.service.StudentService;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentDAO studentDAO;
    @Override
    public PageVO listStudent(Integer current,Integer pageSize,Student student) {
//        Example<Student> example = Example.of(student);
        Specification<Student> specification = new Specification<Student>() {
            @Override
            public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                ArrayList<Predicate> list = new ArrayList();
                if(student.getName() != null && !student.getName().equals("")){
                    list.add(criteriaBuilder.like(root.get("name"),"%" + student.getName() + "%"));
                }
                if(student.getGender() != null && !student.getGender().equals("")){
                    list.add(criteriaBuilder.equal(root.get("gender"),student.getGender()));
                }
                if(student.getAge() != null){
                    list.add(criteriaBuilder.equal(root.get("age"),student.getAge()));
                }
                return criteriaBuilder.and(list.toArray(new Predicate[0]));
            }
        };
        Page page = studentDAO.findAll(specification, PageRequest.of(current - 1,pageSize));

        PageVO pageVO = new PageVO(page);
        return pageVO;
    }

    @Override
    @Transactional
    public void deleteByGender(String gender) {
        studentDAO.deleteByGender(gender);
    }
}
